package com.dd.service;

import com.dd.controller.MainController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.List;

public class MainService {
    private static final Logger log = LoggerFactory.getLogger(MainController.class);

    public String handleGenOneTable(String tableName, String dbName) {
        long startTime = System.currentTimeMillis();
        StringBuilder ddlTable = new StringBuilder();
        tableName = tableName.trim();
        boolean b = false;
        try {
            b = JdbcSchemaCompareUtil.checkTableExist(JdbcConnectionFactory.getSourceConnection(dbName), tableName);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if (!b) {
            log.error("表 {} 在源数据库中不存在", tableName);
            ddlTable.append("\n")
                    .append("-- ")
                    .append(tableName)
                    .append("表在源数据库中不存在\n");
            return "";
        }
        try {
            if (!JdbcSchemaCompareUtil.checkTableExist(JdbcConnectionFactory.getTargetConnection(dbName), tableName)) {
                String createTableSQL = JdbcSchemaCompareUtil.getCreateTableSQL(dbName, tableName);
                ddlTable.append("\n")
                        .append("-- ")
                        .append(tableName)
                        .append("表新增")
                        .append("\n")
                        .append(createTableSQL)
                        .append("\n");
            } else {
                List<String> strings = JdbcSchemaCompareUtil.compareTableStructure(dbName, tableName);
                if (strings != null && !strings.isEmpty()) {
                    ddlTable.append("\n")
                            .append("-- ")
                            .append(tableName)
                            .append("表变动")
                            .append("\n");
                    for (String item : strings) {
                        ddlTable.append(item)
                                .append("\n");
                    }
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        long executionTime = System.currentTimeMillis() - startTime;
        log.info("{}.{}，耗时: {} 毫秒", dbName, tableName, executionTime);
        return ddlTable.length() == 0 ? "" : ddlTable.toString();
    }
}
